package com.example.androidtest4

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import cn.edu.sicnu.cardgame.CardMatchingGame
import kotlin.math.max


class MainActivity2 : AppCompatActivity(), View.OnClickListener {
    val cardButtons=mutableListOf<Button>()//收集到所有按钮，CardButtons是一个可变的列表
    lateinit var score: TextView
    lateinit var game: CardMatchingGame//延迟初始化，CardMatchingGame的实例，只有当唤起OnCreate才会进行初始化
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)
        score=findViewById(R.id.score)
        val reset=findViewById<Button>(R.id.reset)
        val cancel=findViewById<Button>(R.id.cancel_button)
        val gridlayout= findViewById<GridLayout>(R.id.gridlayout)
        for(v in gridlayout.children) {
            if (v is Button) {//判断是否是一个按钮
                v.setOnClickListener(this)
                cardButtons.add(v)//列表里面添加这个按钮,去进行配对计算
            }
            game = CardMatchingGame(cardButtons.count())//创建游戏实例
            updateUI()//刷新游戏界面
        }
        reset.setOnClickListener {
            game.score= 0
            updateUI()
        }

        //取消按钮
        cancel.setOnClickListener {
            val intent= Intent()
            val currentScore=game.score
            intent.putExtra("SECOND_MSG",currentScore)
            setResult(RESULT_OK,intent)
            finish()
        }
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
    fun updateUI(){
        for(button in cardButtons){
            val index=cardButtons.indexOf(button)
            val card=game.cardAtIndex(index)
            button.isEnabled=!card.isMatched
            if(card.isChosen){
                button.text=card.toString()
                button.setBackgroundColor(Color.WHITE)
            }
            else{
                button.text=""
                button.setBackgroundResource(R.drawable.pai1)
            }
        }
        score.text= String.format("%s%d","Score:",game.score)
    }
    override fun onClick(v: View?) {
        if(v is Button){
            val index=cardButtons.indexOf(v)//获取按下的是哪一个按钮
            game.chooseCardAtIndex(index)//进行运算
            updateUI()
        }
    }
}